<route lang="jsonc">{
  "style": {
    "navigationBarTitleText": "已回款",
    "navigationBarBackgroundColor": "#ffa622",
    "navigationBarTextStyle": "white"
  }
}</route>

<script lang="ts" setup>
import { onLoad } from '@dcloudio/uni-app'
import { ref, watch } from 'vue'
import { repaymentData } from '@/api/lending'
import { getRepayment, loanOrderList } from '@/api/user'

// 搜索关键词
const searchKeyword = ref('')

// 防抖定时器
let debounceTimer: NodeJS.Timeout | null = null

// 总体统计数据 - 直接使用接口字段名
const overallStats = ref({
  total_principal: 0, // 总本金
  total_repayment_amount: 0, // 总回款金额
  left_principal: 0, // 待还本金
  left_interest: 0, // 待收利息
  has_repayment_amount: 0, // 已回款金额
  progress: 0, // 进度
  due_cnt: 0, // 逾期借款笔数
})

// 获取回款统计数据
async function fetchRepaymentStats() {
  try {
    const data = await repaymentData()
    // 直接赋值接口返回的数据
    overallStats.value = {
      total_principal: data.total_principal || 0,
      total_repayment_amount: data.total_repayment_amount || 0,
      left_principal: data.left_principal || 0,
      left_interest: data.left_interest || 0,
      has_repayment_amount: data.has_repayment_amount || 0,
      progress: data.progress || 0,
      due_cnt: data.due_cnt || 0,
    }
  }
  catch (error) {
    console.error('获取回款统计数据失败:', error)
    uni.showToast({
      title: '获取数据失败',
      icon: 'error',
    })
  }
}

// 回款记录数据 - 替换为响应式数据
const repaymentList = ref([])

// 获取回款记录数据
async function fetchRepaymentList() {
  try {
    const res = await loanOrderList({
      page: 1,
      size: 9999,
      repayment_tp: 0,
      keyword: searchKeyword.value,
    })
    // 只获取已回款的记录（有 payment_time 的记录）
    repaymentList.value = res.list.filter(item => item.payment_time)
    console.log(repaymentList.value)
  }
  catch (error) {
    console.error('获取回款记录失败:', error)
    uni.showToast({
      title: '获取回款记录失败',
      icon: 'error',
    })
  }
}

// 获取还款方式文本
const getRepaymentMethodText = {
  1: '分期还款',
  2: '利润分成',
}
// 防抖搜索函数
function debouncedSearch() {
  if (debounceTimer) {
    clearTimeout(debounceTimer)
  }
  debounceTimer = setTimeout(() => {
    fetchRepaymentList()
  }, 500) // 500ms 防抖延迟
}

// 监听搜索关键词变化
watch(searchKeyword, () => {
  debouncedSearch()
})
// 格式化金额
function formatAmount(amount: number) {
  return amount.toFixed(2)
}

// 计算回款进度
function getProgress(repaid: number, total: number) {
  return Math.round((repaid / total) * 100)
}

// 查看详情
function viewDetail(item: any) {
  uni.showToast({
    title: '查看详情功能待开发',
    icon: 'none',
  })
}

onLoad(() => {
  console.log('已回款页面加载完成')
  fetchRepaymentStats()
  fetchRepaymentList()
})

// 还款明细弹窗相关状态
const showRepaymentDetailModal = ref(false)
const detailRepaymentList = ref([])
const repaymentQuery = reactive({
  is_pay: '-1',
  start_date: '',
  end_date: '',
  page: 1,
  size: 999,
})

// 获取状态类型
function getStatusType(status: boolean) {
  switch (status) {
    case true:
      return 'success'
    case false:
      return 'warning'
  }
}

// 获取状态文本
function getStatusText(status: boolean) {
  switch (status) {
    case true:
      return '已支付'
    case false:
      return '待还款'
  }
}

// 获取还款记录并显示弹窗
function getRepaymentList(id) {
  getRepayment(id, repaymentQuery).then((res) => {
    console.log(res, '还款明细')
    detailRepaymentList.value = res.list || []
    showRepaymentDetailModal.value = true
  })
}

// 关闭还款明细弹窗
function closeRepaymentDetailModal() {
  showRepaymentDetailModal.value = false
}
</script>

<template>
  <view class="repayment-page">
    <!-- 回款进度统计 -->
    <view class="stats-container">
      <view class="stats-header">
        <text class="stats-title">回款进度</text>
      </view>

      <!-- 进度条区域 -->
      <view class="progress-overview">
        <view class="progress-amounts">
          <view class="amount-left">
            <text class="amount-number">{{ (overallStats.has_repayment_amount / 10000).toFixed(1) }}万</text>
          </view>
          <view class="amount-right">
            <text class="amount-number">{{ (overallStats.total_principal / 10000).toFixed(1) }}万</text>
          </view>
        </view>
        <view class="progress-bar-overview">
          <view class="progress-track-overview">
            <view class="progress-fill-overview" :style="{ width: `${overallStats.progress * 100}%` }">
              <text class="percentage-text">{{ overallStats.progress * 100 }}%</text>
            </view>
          </view>
        </view>
      </view>
      <!-- 统计卡片 -->
      <view class="stats-card">
        <view class="stats-row">
          <view class="stat-item large">
            <text class="stat-number">{{ overallStats.left_principal.toLocaleString() }}</text>
            <text class="stat-label">待还本金</text>
          </view>
          <view class="stat-item large">
            <text class="stat-number">{{ overallStats.left_interest.toLocaleString() }}</text>
            <text class="stat-label">待收利息</text>
          </view>
          <view class="stat-item large">
            <text class="stat-number highlight">{{ overallStats.due_cnt }}笔</text>
            <text class="stat-label">逾期借款</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 搜索框 -->
    <view class="search-container">
      <view class="search-box">
        <uni-icons type="search" size="18" color="#999" />
        <input v-model="searchKeyword" class="search-input" placeholder="请输入姓名 / 手机号查询"
          placeholder-style="color: #999;">
      </view>
    </view>

    <!-- 回款记录列表 -->
    <view class="list-container">
      <view v-if="repaymentList.length === 0" class="empty-state">
        <text class="empty-text">暂无回款记录</text>
      </view>

      <!-- 修改为与 reimburseList.vue 一致的结构 -->
      <view v-for="item in repaymentList" :key="item.id" class="section">
        <view class="section-header">
          <text class="section-title">{{ item.user_name }}-{{ item.user_telephone }}</text>
          <view class="more-section text-[#999]" @click="getRepaymentList(item.id)">
            <text class="more-text">明细</text>
            <uni-icons type="right" size="14" color="#999" />
          </view>
        </view>
        <view class="repayment-card">
          <view class="repayment-header">
            <text class="loan-id">{{ item.order_id }}</text>
            <text v-if="item.account_bank_user" class="loan-id">
              回款账户：
              {{ item.account_bank_user }}-{{ item.account_bank_name }}-{{ item.account_bank_no }}
            </text>
            <text class="loan-id">产品：{{ item.product_name }}</text>
            <view class="loan-amount-info">
              <text class="loan-amount-label">配资金额：</text>
              <text class="loan-amount-value">
                ¥{{ formatAmount(item.principal) }}（{{ item.annual_interest_rate
                }}%）
              </text>
            </view>
          </view>

          <!-- 已还完状态显示 -->
          <view v-if="item.is_finished === 1" class="completed-status">
            <view class="completed-badge">
              <text class="completed-text">✓ 已还完</text>
            </view>
            <view class="completion-info">
              <text class="completion-text">恭喜！该笔配资已全部还清</text>
              <text class="total-periods">共{{ item.installment_periods }}期</text>
            </view>
          </view>

          <!-- 未还完状态显示 -->
          <template v-else>
            <!-- 当期还款信息 -->
            <view class="current-repayment-info" :class="{ overdue: item.is_due }">
              <!-- 逾期提示 -->
              <view v-if="item.is_due" class="overdue-warning">
                <text class="overdue-text">已逾期</text>
              </view>
              <view class="repayment-content">
                <view class="current-period">
                  <text class="period-label">当期还款</text>
                  <text class="period-value">第{{ item.period }}期 / 共{{ item.installment_periods }}期</text>
                </view>
                <view class="due-date-info">
                  <text class="due-label">当期还款时间</text>
                  <text class="due-value" :class="{ 'overdue-date': item.is_due }">{{ item.repayment_date }}</text>
                </view>
              </view>
            </view>

            <!-- 当期应还明细 -->
            <view class="repayment-details">
              <view class="detail-title">
                <text class="title-text">当期应还明细</text>
              </view>
              <view class="detail-items">
                <view class="detail-item">
                  <view class="item-left">
                    <view class="item-dot principal-dot" />
                    <text class="item-label">本金</text>
                  </view>
                  <text class="item-amount">¥{{ formatAmount(item.monthly_principal) }}</text>
                </view>
                <view class="detail-item">
                  <view class="item-left">
                    <view class="item-dot interest-dot" />
                    <text class="item-label">利息</text>
                  </view>
                  <text class="item-amount">¥{{ formatAmount(item.monthly_interest) }}</text>
                </view>
                <view class="detail-item total-item">
                  <view class="item-left">
                    <text class="item-label total-label">本期应还总额</text>
                  </view>
                  <text class="item-amount total-amount">¥{{ formatAmount(item.repayment_amount) }}</text>
                </view>
              </view>
            </view>

            <!-- 剩余还款信息 -->
            <view class="remaining-info">
              <view class="remaining-title">
                <text class="title-text">剩余还款信息</text>
              </view>
              <view class="remaining-items">
                <view class="remaining-item">
                  <text class="remaining-label">剩余本金</text>
                  <text class="remaining-value">¥{{ formatAmount(item.left_principal) }}</text>
                </view>
                <view class="remaining-item">
                  <text class="remaining-label">剩余利息</text>
                  <text class="remaining-value">¥{{ formatAmount(item.left_interest) }}</text>
                </view>
                <view class="remaining-item total-remaining">
                  <text class="remaining-label total-label">剩余总额</text>
                  <text class="remaining-value total-value">¥{{ formatAmount(item.total_repayment_amount) }}</text>
                </view>
              </view>
            </view>
          </template>
        </view>
      </view>
    </view>
    <!-- 还款详情弹窗 -->
    <wd-popup v-model="showRepaymentDetailModal" position="bottom" height="80%">
      <view class="repayment-detail-popup">
        <view class="popup-header">
          <text class="popup-title">还款详情</text>
          <wd-icon name="close" class="close-icon" @click="closeRepaymentDetailModal" />
        </view>
        <view class="table-container">
          <wd-table :data="detailRepaymentList" :height="400" stripe border>
            <wd-table-col prop="period" label="期数" width="50" />
            <wd-table-col prop="repayment_date" label="还款日期" width="100" />
            <wd-table-col prop="is_pay" label="还款状态" width="100">
              <template #value="{ row }">
                <wd-tag :type="getStatusType(row.is_pay)">
                  {{ getStatusText(row.is_pay) }}
                </wd-tag>
                <view>{{ row.actual_repayment_time ? row.actual_repayment_time.split(' ')[0] : '' }}</view>
              </template>
            </wd-table-col>
            <wd-table-col prop="finance_confirm" label="财务确认" width="100">
              <template #value="{ row }">
                <wd-tag :type="row.finance_confirm ? 'success' : 'warning'">
                  {{ row.finance_confirm ? '已确认' : '待确认' }}
                </wd-tag>
                <view> {{ row.finance_confirm_time ? row.finance_confirm_time.split(' ')[0] : '' }}</view>
              </template>
            </wd-table-col>
            <wd-table-col prop="principal" label="应还" width="120">
              <template #value="{ row }">
                <view>本金：{{ row.principal }}</view>
                <view>利息：{{ row.interest }}</view>
                <view>总额：{{ row.repayment_amount }}</view>
              </template>
            </wd-table-col>
          </wd-table>
        </view>
      </view>
    </wd-popup>
  </view>
</template>

<style lang="scss" scoped>
.repayment-page {
  background-color: #f6f6f6;
  min-height: 100vh;
  padding-bottom: 20rpx;
}

/* 新增统计区域样式 */
.stats-container {
  background-color: #fff;
  margin-bottom: 20rpx;
  padding: 30rpx;
}

.stats-header {
  margin-bottom: 30rpx;
}

.stats-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.progress-overview {
  margin-bottom: 30rpx;
}

.progress-amounts {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20rpx;
}

.amount-left,
.amount-right {
  display: flex;
  align-items: center;
}

.amount-number {
  font-size: 28rpx;
  color: #666;
  font-weight: 500;
}

.progress-bar-overview {
  margin-bottom: 15rpx;
}

.progress-track-overview {
  height: 30rpx;
  background-color: #e5e5e5;
  border-radius: 8rpx;
  overflow: hidden;
}

.progress-fill-overview {
  height: 100%;
  background-color: #ffa622;
  transition: width 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
}

.progress-percentage {
  text-align: center;
}

.percentage-text {
  font-size: 20rpx;
  color: #fff;
  font-weight: 500;
}

.stats-card {
  background: #ffa622;
  border-radius: 20rpx;
  padding: 40rpx 30rpx;
  color: #fff;
}

.stats-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;

  &.large {
    align-items: flex-start;

    .stat-number {
      font-size: 48rpx;
      font-weight: bold;
      margin-bottom: 10rpx;
    }

    .stat-label {
      font-size: 24rpx;
      opacity: 0.9;
    }
  }
}

.stat-number {
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 8rpx;

  &.small {
    font-size: 28rpx;
  }

  &.highlight {
    color: #fff;
  }
}

.stat-label {
  font-size: 22rpx;
  opacity: 0.9;
}

/* 原有样式保持不变 */
.search-container {
  padding: 20rpx;
  background-color: #fff;
  margin-bottom: 20rpx;
}

.search-box {
  display: flex;
  align-items: center;
  background-color: #f5f5f5;
  border-radius: 25rpx;
  padding: 15rpx 20rpx;
  gap: 15rpx;
}

.search-input {
  flex: 1;
  font-size: 28rpx;
  color: #333;
}

.list-container {
  padding: 0 20rpx;
}

.empty-state {
  text-align: center;
  padding: 100rpx 0;
}

.empty-text {
  color: #999;
  font-size: 28rpx;
}

// 区块样式组
.section {
  margin-bottom: 30rpx;
  background-color: #fff;
  border-radius: 24rpx;
  overflow: hidden;

  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 32rpx;
    border-bottom: 2rpx solid #f0f0f0;

    .section-title {
      font-size: 32rpx;
      font-weight: 600;
      color: #333;
    }
  }
}

// 还款卡片样式组
.repayment-card {
  padding: 32rpx;
  background: #fff;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
  padding-top: 20rpx;

  .repayment-header {
    margin-bottom: 24rpx;
    padding-bottom: 20rpx;
    border-bottom: 1rpx solid #f0f0f0;

    .loan-id {
      font-size: 28rpx;
      display: block;
      margin-bottom: 8rpx;
    }

    .loan-amount-info {
      display: flex;
      align-items: center;
      margin-top: 8rpx;

      .loan-amount-label {
        font-size: 26rpx;
        margin-right: 8rpx;
      }

      .loan-amount-value {
        font-size: 30rpx;
        font-weight: 600;
        color: #ff6b35;
      }
    }
  }

  // 当期还款信息
  .current-repayment-info {
    // display: flex;
    justify-content: space-between;
    margin-bottom: 24rpx;
    padding: 20rpx;
    background: linear-gradient(135deg, #f8f9ff 0%, #f0f4ff 100%);
    border-radius: 12rpx;
    border-left: 4rpx solid #4285f4;

    // 逾期状态样式
    &.overdue {
      background: linear-gradient(135deg, #fff5f5 0%, #ffebee 100%);
      border-left: 4rpx solid #ff4757;

      .period-value,
      .due-value {
        color: #ff4757;
      }
    }

    // 逾期警告提示
    .overdue-warning {
      background: #ff4757;
      color: #fff;
      padding: 8rpx 16rpx;
      border-radius: 20rpx;
      font-size: 22rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 6rpx;
      margin-bottom: 16rpx;
      box-shadow: 0 2rpx 8rpx rgba(255, 71, 87, 0.3);

      .overdue-text {
        font-weight: 600;
        letter-spacing: 1rpx;
      }
    }

    // 还款内容容器
    .repayment-content {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .current-period,
    .due-date-info {
      display: flex;
      flex-direction: column;
      align-items: center;

      .period-label,
      .due-label {
        font-size: 24rpx;
        color: #666;
        margin-bottom: 6rpx;
      }

      .period-value,
      .due-value {
        font-size: 28rpx;
        font-weight: 600;
        color: #4285f4;
        transition: color 0.3s ease;

        &.overdue-date {
          color: #ff4757;
        }
      }
    }
  }

  // 当期应还明细
  .repayment-details {
    margin-bottom: 24rpx;

    .detail-title {
      margin-bottom: 16rpx;

      .title-text {
        font-size: 28rpx;
        font-weight: 600;
        color: #333;
      }
    }

    .detail-items {
      background: #fafafa;
      border-radius: 12rpx;
      padding: 20rpx;

      .detail-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16rpx;

        &:last-child {
          margin-bottom: 0;
        }

        &.total-item {
          padding-top: 16rpx;
          border-top: 1rpx solid #e0e0e0;
          margin-top: 8rpx;
        }

        .item-left {
          display: flex;
          align-items: center;

          .item-dot {
            width: 12rpx;
            height: 12rpx;
            border-radius: 50%;
            margin-right: 12rpx;

            &.principal-dot {
              background-color: #4285f4;
            }

            &.interest-dot {
              background-color: #ff9500;
            }
          }

          .item-label {
            font-size: 26rpx;
            color: #666;

            &.total-label {
              font-weight: 600;
              color: #333;
            }
          }
        }

        .item-amount {
          font-size: 26rpx;
          font-weight: 600;
          color: #333;

          &.total-amount {
            font-size: 30rpx;
            color: #ff6b35;
          }
        }
      }
    }
  }

  // 剩余还款信息
  .remaining-info {
    margin-bottom: 24rpx;

    .remaining-title {
      margin-bottom: 16rpx;

      .title-text {
        font-size: 28rpx;
        font-weight: 600;
        color: #333;
      }
    }

    .remaining-items {
      background: linear-gradient(135deg, #fff8f0 0%, #fff2e6 100%);
      border-radius: 12rpx;
      padding: 20rpx;
      border: 1rpx solid #ffe4cc;

      .remaining-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 12rpx;

        &:last-child {
          margin-bottom: 0;
        }

        &.total-remaining {
          padding-top: 12rpx;
          border-top: 1rpx solid #ffe4cc;
          margin-top: 8rpx;
        }

        .remaining-label {
          font-size: 26rpx;
          color: #666;

          &.total-label {
            font-weight: 600;
            color: #333;
          }
        }

        .remaining-value {
          font-size: 26rpx;
          font-weight: 600;
          color: #ff9500;

          &.total-value {
            font-size: 30rpx;
            color: #ff6b35;
          }
        }
      }
    }
  }
}

// 已还完状态样式
.completed-status {
  text-align: center;
  padding: 40rpx 20rpx;

  .completed-badge {
    background: linear-gradient(135deg, #52c41a 0%, #73d13d 100%);
    border-radius: 50rpx;
    padding: 16rpx 32rpx;
    display: inline-block;
    margin-bottom: 24rpx;
    box-shadow: 0 4rpx 12rpx rgba(82, 196, 26, 0.3);

    .completed-text {
      font-size: 28rpx;
      color: #fff;
      font-weight: 600;
      letter-spacing: 1rpx;
    }
  }

  .completion-info {
    .completion-text {
      display: block;
      font-size: 26rpx;
      color: #52c41a;
      font-weight: 500;
      margin-bottom: 8rpx;
    }

    .total-periods {
      display: block;
      font-size: 24rpx;
      color: #999;
    }
  }
}

/* 在现有样式中添加借款人信息样式 */
.borrower-info {
  margin: 10rpx 0;
  padding: 15rpx 0;
  border-top: 1rpx solid #f0f0f0;
  border-bottom: 1rpx solid #f0f0f0;
}

.borrower-name,
.borrower-phone {
  display: block;
  font-size: 28rpx;
  color: #666;
  margin-bottom: 8rpx;
}

.borrower-name {
  color: #333;
  font-weight: 500;
}

// 明细按钮样式
.more-section {
  display: flex;
  align-items: center;
  gap: 8rpx;
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
  background-color: #f5f5f5;
  transition: all 0.3s ease;

  &:active {
    background-color: #e0e0e0;
  }

  .more-text {
    font-size: 24rpx;
    color: #999;
  }
}

// 还款详情弹窗样式
.repayment-detail-popup {
  background: #fff;
  border-radius: 20rpx 20rpx 0 0;
  height: 100%;
  display: flex;
  flex-direction: column;

  .popup-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 32rpx;
    border-bottom: 1rpx solid #f0f0f0;

    .popup-title {
      font-size: 32rpx;
      font-weight: 600;
      color: #333;
    }

    .close-icon {
      font-size: 32rpx;
      color: #999;
    }
  }

  .table-container {
    flex: 1;
    padding: 20rpx;
    overflow: hidden;
  }
}
</style>
